/**
 * 用户分组计数接口测试用例
 *
 * Created by snowingsea on 2020/02/02.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const { statusKind, roleKind } = require('./../../../../phoenix/models/users');

module.exports = describe('/GET group/users.json', function () {
  const url = '/group/users.json';
  const administrator = new Administrator();
  const newUserIds = [];
  const group = { status: [], roles: [] };
  before(function (done) {
    administrator.createRandomUsers(30)
      .then((users) => {
        users.forEach(({ userId }) => {
          newUserIds.push(userId);
        });
        return administrator.randomUpdateStatus4Users(users);
      })
      .then(() => administrator.getAllUsers())
      .then((users) => {
        group.total = users.length;
        const statusCount = new Map();
        const roleCount = new Map();
        Object.keys(statusKind).forEach((key) => {
          statusCount.set(statusKind[key], 0);
        });
        Object.keys(roleKind).forEach((key) => {
          roleCount.set(roleKind[key], 0);
        });
        users.forEach(({ status, role }) => {
          statusCount.set(status, statusCount.get(status) + 1);
          Object.keys(roleKind).forEach((key) => {
            if ((roleKind[key] & role) > 0) { // eslint-disable-line no-bitwise
              roleCount.set(roleKind[key], roleCount.get(roleKind[key]) + 1);
            }
          });
        });

        Object.keys(statusKind).forEach((key) => {
          group.status.push({
            status: statusKind[key],
            name: key,
            count: statusCount.get(statusKind[key]),
          });
        });
        Object.keys(roleKind).forEach((key) => {
          group.roles.push({
            role: roleKind[key],
            name: key,
            count: roleCount.get(roleKind[key]),
          });
        });
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'get');
  common.should.be.administrator(uri, url, 'get');

  // 正常请求
  it('it should GET group of users', function (done) {
    administrator.login()
      .then(() => {
        chai.request(uri)
          .get(url)
          .set('Authorization', `Bearer ${administrator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(200);
            res.body.should.be.eql(group);
            done();
          });
      })
      .catch(done);
  });
});
